// src/context/AuthContext.jsx
import { createContext, useContext, useState } from "react";
export const AuthContext = createContext();
export const useAuth = () => useContext(AuthContext);

export function AuthProvider({ children }) {

  // 初始化权限按钮状态，从 localStorage 中读取
  // 如果 localStorage 中没有权限按钮，则默认为空数组
  const [authButtons, setAuthButtons] = useState(() => {
    const localAuthButtons = localStorage.getItem("authButtons");
    return localAuthButtons ? JSON.parse(localAuthButtons) : [];
  });



  // 当 setAuthButtons 更新时同步到 localStorage
  // 这样可以确保在应用加载时就有初始权限按钮状态
  // 并且可以在其他组件中通过 useAuth 获取和更新权限按钮状态
  const setAuthButtonsAndPersist = (data) => {
    setAuthButtons(data);
    localStorage.setItem("authButtons", JSON.stringify(data));
  }



  return (
    <AuthContext.Provider value={{ authButtons, setAuthButtons: setAuthButtonsAndPersist }}>
      {children}
    </AuthContext.Provider>
  );
}